﻿#region Copyrights Notice
//©2009 Microsoft Corporation.  All rights reserved.
#endregion


using System;
using System.DirectoryServices;
using System.Globalization;
using System.Security.Cryptography;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using Microsoft.CISG.BitlockerRecovery.BL;
using Microsoft.CISG.BitlockerRecovery.CDE;
using Microsoft.Security.Application;

namespace BitlockerRecovery
{
    public partial class SelfService : System.Web.UI.Page
    {
        private IdentityCDE UserInfo;

        protected void Page_Load(object sender, EventArgs e)
        {
                if ((string)Session["Accepted"]!="true")
                {
                    Response.Redirect("Agreement.aspx");
                }
            
        }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        protected void Submit_Click(object sender, EventArgs e)
        {
            string AuthUser = HttpContext.Current.User.Identity.Name.ToLower(CultureInfo.CurrentCulture);
            UserInfo = CommonBL.GetUserADData(AuthUser);

            string Requestor = UserInfo.UserAlias;
            string EmailMngr = UserInfo.UserManagerAlias;
            string MachineOwner;
            char[] StrSeperator;
            string[] aryMachineOwner;

            Validate("UserSearch");
            if (Page.IsValid)
            {
                try
                {
                    string SrchRecoveryGUID = RecoveryGUID.Text.ToString().ToUpper(CultureInfo.CurrentCulture);
                    UserInfo = CommonBL.SearchGUID(SrchRecoveryGUID, UserInfo.UserDomain + "\\" + UserInfo.UserAlias, UserInfo.UserDomain + "\\" + UserInfo.UserAlias, 1);
                    if (UserInfo.RecoveryPassword != null)
                    {
                        MachineNameLabel.Text = AntiXss.HtmlEncode(UserInfo.MachineName);
                        UserLabel.Text = AntiXss.HtmlEncode(UserInfo.MachineOwner);
                        RecoveryGUIDLabel.Text = UserInfo.RecoveryGUID.ToUpper(CultureInfo.CurrentCulture);
                        StrSeperator = new char[] { '\\' };

                        if (UserInfo.MachineOwner == "unknown"||String.IsNullOrEmpty(UserInfo.MachineOwner))
                        {
                            MachineOwner = "";
                        }
                        else
                        {
                            aryMachineOwner = new string[2];
                            aryMachineOwner = UserInfo.MachineOwner.Split(StrSeperator);

                            MachineOwner = aryMachineOwner[1];
                        }

                        RecoveryPasswordLabel.Text = Encryption.DecryptBitlocker(UserInfo.RecoveryPassword);
                        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                        string str = enc.GetString(UserInfo.KeyPackage);
                        HdKeyPackage.Text = str;
                        string UserTPMHash = enc.GetString(UserInfo.TPMHash);

                        if (UserInfo.TPMFound && !UserTPMHash.StartsWith("\0\0\0\0\0", StringComparison.Ordinal))
                        {
                            hdTPMHash.Text = Encryption.DecryptBitlocker(UserInfo.TPMHash);
                            TPMHashButton.Enabled = true;
                        }
                        else
                        {
                            TPMHashButton.Enabled = false;
                        }
                        try
                        {
                            Email.SendEmail(Requestor, "Requestor", Requestor, UserInfo, DateTime.Today.ToShortDateString());
                            Email.SendEmail(EmailMngr, "Manager", Requestor, UserInfo, DateTime.Today.ToShortDateString());
                            if (Requestor != MachineOwner)
                            {
                                Email.SendEmail(MachineOwner, "Manager", Requestor, UserInfo, DateTime.Today.ToShortDateString());
                            }
                        }
                        catch (ArgumentNullException ane)
                        {
                            LabelMessage.Text = "An error has occurred.  It has been logged for follow-up by the system administrator.";
                            LogErrorsBL.InsertErrorLog("SendEmail ArgumentNullException", "Param:" + ane.ParamName + "/" + ane.Message + ": Stack Trace: " + ane.StackTrace);
                        }
                        catch (ArgumentException ae)
                        {
                            LabelMessage.Text = "An error has occurred.  It has been logged for follow-up by the system administrator.";
                            LogErrorsBL.InsertErrorLog("SendEmail ArgumentException", "Param:" + ae.ParamName + "/" + ae.Message + ": Stack Trace: " + ae.StackTrace);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            LabelMessage.Text = "An error has occurred.  It has been logged for follow-up by the system administrator.";
                            LogErrorsBL.InsertErrorLog("SendEmail InvalidOperationException", "Source:" + ioe.Source + "/" + ioe.Message + ": Stack Trace: " + ioe.StackTrace);
                        }
                        catch (SmtpException se)
                        {
                            LabelMessage.Text = "An error has occurred.  It has been logged for follow-up by the system administrator.";
                            LogErrorsBL.InsertErrorLog("SendEmail SmtpException", "SMTP Status Code:" + se.StatusCode + "/" + se.Message + ": Stack Trace: " + se.StackTrace);
                        }
                        SelfServiceMultiview.SetActiveView(ResultsView);
                    }
                    else
                    {
                        LabelMessage.Text = "No records found";
                        SelfServiceMultiview.SetActiveView(SearchView);
                    }
                }
                catch (CryptographicException ce)
                {
                    LabelMessage.Text = "An error has occurred.  It has been logged for follow-up by the system administrator.";
                    LogErrorsBL.InsertErrorLog("CryptographicException", "Source:" +ce.Source + ": " + ce.Message + ": Stack Trace: " + ce.StackTrace);
                }
            }
            else
            {
                LabelMessage.Text = "An error has occurred.  It has been logged for follow-up by the system administrator.";
                LogErrorsBL.InsertErrorLog(Request.Path.ToString(), Requestor + ": Client-side validation has been bypassed but server-side validation failed.");
                SelfServiceMultiview.SetActiveView(SearchView);

            }
    
        }
        protected void Back_OnClick(object sender, EventArgs e)
        {
            SelfServiceMultiview.SetActiveView(SearchView);
            hdTPMHash.Visible = false;
            HdKeyPackage.Visible = false;
            RecoveryGUID.Text = null;
            LabelMessage.Text = null;

        }
        protected void DownloadTPM_OnClick(object sender, EventArgs e)
        {
            string FileName = MachineNameLabel.Text + System.Configuration.ConfigurationSettings.AppSettings["TPMHashFileName"];
            try
            {
                string TPMXML = CommonBL.GenerateTpmxml(hdTPMHash.Text);
                DownloadFile(FileName, TPMXML);
            }
            catch (CryptographicException ex)
            {
                LabelMessage.Text = "An error has occurred.  It has been logged for follow-up by the system administrator.";
                LogErrorsBL.InsertErrorLog(Request.Path.ToString(), Request.RawUrl + ": " + ex.Message + ": Stack Trace: " + ex.StackTrace);
            }

        }
        protected void DownloadKeyPackage_OnClick(object sender, EventArgs e)
        {
            string FileName = RecoveryGUIDLabel.Text + System.Configuration.ConfigurationSettings.AppSettings["KeyPackageFileName"];

            try
            {
                DownloadFile(FileName, HdKeyPackage.Text);
            }
            catch (HttpException ex)
            {
                LabelMessage.Text = "An error has occurred.  It has been logged for follow-up by the system administrator.";
                LogErrorsBL.InsertErrorLog(Request.Path.ToString(), "Error downloading KeyPackage:" + FileName + ": " + ex.Message + ": Stack Trace: " + ex.StackTrace);
            }

        }
        protected void DownloadFile(string fileName, string fileContent)
        {
            try
            {
                Response.ContentType = "application/x-download";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
                Response.Write(fileContent);
                Response.End();
            }
            catch 
            {
                throw;
            }
        }

    }
}
